require 'utils'

def modify_name(name)
  return name.delete("(TD)")
end

def save_map(parent_id, name)
  map_name = modify_name(name)
  map = nil
  begin
    map = find_map_by_name(map_name)
  rescue Exception => e
    puts e
    map = Map.new
  end
  map.parent_id  = parent_id
  map.japaness_name = map_name
  map.save
  return map
end

def save_town(name, map_id)
  town_name = modify_name(name)
  town = nil
  begin
    town = find_town_by_name(town_name)
  rescue
    town = Town.new
  end
  town.japaness_name = town_name
  town.map = map_id
  town.save
end

def save_dungeon(name, map_id)
  dungeon_name = modify_name(name)
  dungeon = nil
  begin
    dungeon = find_dungeon_by_name(dungeon_name)
  rescue
    dungeon = Dungeon.new
  end
  dungeon.japaness_name = dungeon_name
  dungeon.map = map_id
  dungeon.save
end

File.open('templates/map.txt', 'r') do |file|
  while line = file.gets
    line.chop!
    strs = line.split("\t")
    map_id = save_map(0, strs[1]).id
    next if strs[2].nil?
    next if strs[2].empty?
    sub_maps = strs[2].split("/")
    sub_maps.each do |sub_map|
      sub_map_id = save_map(map_id, sub_map).id
      if sub_map.include? "(T)"
        save_town(sub_map, sub_map_id)
      end
      if sub_map.include? "(D)"
        save_dungeon(sub_map, sub_map_id)
      end
    end
  end
end
